#!/usr/bin/env python3
"""
Cookie格式修复工具
修复cookie.txt文件中的格式问题
"""

import re
from pathlib import Path

def fix_cookie_file(cookie_file_path: str):
    """修复Cookie文件格式"""
    
    cookie_file = Path(cookie_file_path)
    if not cookie_file.exists():
        print(f"❌ Cookie文件不存在: {cookie_file}")
        return False
    
    print(f"🔧 修复Cookie文件: {cookie_file}")
    
    try:
        # 读取原始文件
        with open(cookie_file, 'r', encoding='utf-8') as f:
            content = f.read()
        
        print(f"📄 原始文件大小: {len(content)} 字符")
        
        # 提取cookie1和cookie2
        cookie1_match = re.search(r'cookie1="([^"]*)"', content, re.DOTALL)
        cookie2_match = re.search(r'cookie2="([^"]*)"', content, re.DOTALL)
        
        if not cookie1_match:
            print("❌ 未找到cookie1")
            return False
        
        if not cookie2_match:
            print("❌ 未找到cookie2")
            return False
        
        # 清理Cookie字符串
        cookie1_raw = cookie1_match.group(1)
        cookie2_raw = cookie2_match.group(1)
        
        # 移除换行符和多余空格
        cookie1_clean = cookie1_raw.replace('\n', '').replace('\r', '').strip()
        cookie2_clean = cookie2_raw.replace('\n', '').replace('\r', '').strip()
        
        print(f"✅ cookie1 清理后长度: {len(cookie1_clean)} 字符")
        print(f"✅ cookie2 清理后长度: {len(cookie2_clean)} 字符")
        
        # 验证Cookie格式
        def validate_cookie(cookie_str):
            if not cookie_str:
                return False, "Cookie为空"
            
            # 检查是否包含基本的Cookie字段
            required_fields = ['_lxsdk_cuid', '_lxsdk']
            for field in required_fields:
                if field not in cookie_str:
                    return False, f"缺少必要字段: {field}"
            
            # 检查格式
            pairs = cookie_str.split('; ')
            valid_pairs = 0
            for pair in pairs:
                if '=' in pair and pair.strip():
                    valid_pairs += 1
            
            if valid_pairs < 5:
                return False, f"有效Cookie对太少: {valid_pairs}"
            
            return True, f"包含 {valid_pairs} 个有效Cookie对"
        
        # 验证两个Cookie
        cookie1_valid, cookie1_msg = validate_cookie(cookie1_clean)
        cookie2_valid, cookie2_msg = validate_cookie(cookie2_clean)
        
        print(f"🔍 cookie1 验证: {'✅' if cookie1_valid else '❌'} {cookie1_msg}")
        print(f"🔍 cookie2 验证: {'✅' if cookie2_valid else '❌'} {cookie2_msg}")
        
        if not cookie1_valid or not cookie2_valid:
            print("⚠️ Cookie验证失败，但仍会保存清理后的版本")
        
        # 生成新的文件内容
        new_content = f"""# 清理后的Cookie文件
# 生成时间: {Path(__file__).stat().st_mtime}

cookie1="{cookie1_clean}"

cookie2="{cookie2_clean}"
"""
        
        # 备份原文件
        backup_file = cookie_file.with_suffix('.txt.backup')
        with open(backup_file, 'w', encoding='utf-8') as f:
            f.write(content)
        print(f"💾 原文件已备份到: {backup_file}")
        
        # 写入修复后的文件
        with open(cookie_file, 'w', encoding='utf-8') as f:
            f.write(new_content)
        
        print(f"✅ Cookie文件修复完成!")
        print(f"📊 新文件大小: {len(new_content)} 字符")
        
        return True
        
    except Exception as e:
        print(f"❌ 修复失败: {e}")
        return False

def fix_individual_cookie_files():
    """修复单独的Cookie文件"""
    
    cookie_files = [
        "config/cookies/cookie1.txt",
        "config/cookies/cookie2.txt"
    ]
    
    for cookie_file in cookie_files:
        cookie_path = Path(cookie_file)
        if cookie_path.exists():
            print(f"\n🔧 修复 {cookie_file}")
            
            try:
                with open(cookie_path, 'r', encoding='utf-8') as f:
                    content = f.read().strip()
                
                # 移除可能的引号包装
                if content.startswith('"') and content.endswith('"'):
                    content = content[1:-1]
                
                # 清理换行符
                content = content.replace('\n', '').replace('\r', '').strip()
                
                # 备份
                backup_path = cookie_path.with_suffix('.txt.backup')
                with open(backup_path, 'w', encoding='utf-8') as f:
                    with open(cookie_path, 'r', encoding='utf-8') as orig:
                        f.write(orig.read())
                
                # 写入清理后的内容
                with open(cookie_path, 'w', encoding='utf-8') as f:
                    f.write(content)
                
                print(f"✅ {cookie_file} 修复完成")
                print(f"📊 清理后长度: {len(content)} 字符")
                
            except Exception as e:
                print(f"❌ {cookie_file} 修复失败: {e}")

def main():
    """主函数"""
    print("🍪 Cookie格式修复工具")
    print("="*50)
    
    # 修复主Cookie文件
    main_cookie_file = "config/cookie.txt"
    if Path(main_cookie_file).exists():
        print("1. 修复主Cookie文件...")
        fix_cookie_file(main_cookie_file)
    else:
        print(f"⚠️ 主Cookie文件不存在: {main_cookie_file}")
    
    # 修复单独的Cookie文件
    print("\n2. 修复单独Cookie文件...")
    fix_individual_cookie_files()
    
    print("\n" + "="*50)
    print("🎉 Cookie修复完成!")
    print("\n建议:")
    print("1. 检查修复后的Cookie文件")
    print("2. 重新运行批量爬取测试")
    print("3. 如有问题，可以从.backup文件恢复")

if __name__ == "__main__":
    main()
